package com.qd.common.sys.domain.sendmsg;

import com.alibaba.fastjson2.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class UrlParams {
    /**
     * 属性
     */
    private HashMap<String, String> properties;

    public void free() {
        Optional.ofNullable(properties).ifPresent(HashMap::clear);
    }

    public void addProp(String name, String value) {
        if (properties == null) {
            properties = new HashMap<>();
        }
        properties.put(name, value);
    }

    public void removeProp(String name) {
        if (properties != null) {
            properties.remove(name);
        }
    }

    public boolean contains(String name) {
        if (properties != null) {
            return properties.containsKey(name);
        }
        return false;
    }

    public String getProp(String name) {
        if (properties != null) {
            return properties.get(name);
        }
        return null;
    }

    public boolean isEmpty() {
        if (properties != null) {
            return properties.isEmpty();
        }
        return true;
    }

    public int size() {
        if (properties != null) {
            return properties.size();
        }
        return 0;
    }

    public Map<String, String> getProperties() {
        if (properties == null) {
            return java.util.Collections.emptyMap();
        }
        return properties;
    }

    public void read(JSONObject content) {
        JSONObject jsonObject = content.getJSONObject("properties");
        if (jsonObject != null) {
            properties = new HashMap<>();
            for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                if (entry.getValue() instanceof String) {
                    properties.put(entry.getKey(), (String) entry.getValue());
                }
            }
        }
    }

    public void write(JSONObject content) {
        if (properties != null && !properties.isEmpty()) {
            JSONObject jsonObject = new JSONObject();
            content.put("properties", jsonObject);
            for (Map.Entry<String, String> entry : properties.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
        }
    }
}
